#include "main.h"

int SVM;											//人体加速度向量幅值SVM和微分加速度幅值的绝对平均值DSVM是区分人体运动状态的重要参量。SVM通过计算加速度幅度表征人体运动的剧烈程度，其值越大表明运动越剧烈。

void *pthread_mpu6050_read(void * arg)
{
	arg = arg;
	int fd;
	int16_t databuf[7];
	int16_t gyro_x_adc, gyro_y_adc, gyro_z_adc;
	int16_t accel_x_adc, accel_y_adc, accel_z_adc;
	int16_t temp_adc;
	u_int8_t i=10;
	int ret = 0;
	
	fd = open("/dev/mpu6050", O_RDWR);
	if(fd < 0) {
		printf("can't open file /dev/mpu6050\r\n");
		return NULL;
	}
 
	while (1) {
		ret = read(fd, databuf, sizeof(databuf));
		if(ret == 0) { 			/* 数据读取成功 */
			accel_x_adc = databuf[0];
			accel_y_adc = databuf[1];
			accel_z_adc = databuf[2];
			gyro_x_adc = databuf[3];
			gyro_y_adc = databuf[4];
			gyro_z_adc = databuf[5];
			temp_adc = databuf[6];

			SVM = sqrt(pow(accel_x_adc,2)+  pow(accel_y_adc,2) + pow(accel_z_adc,2));
			if( SVM>23000 || SVM<12000 )
			{
					i = 0;
			}
				i++;
				if( i<=10 )
				{
					printf("人员跌倒\n");
					blance_flag = 1;
					if(beep_fd == 0)
						beep_fd = open("/dev/beep",O_RDWR);
				}
				else 
				{
					i = 10;
					blance_flag = 0;
				}
			printf("加速度Acc. X = %d, Y = %d, Z = %d\n", accel_x_adc, accel_y_adc, accel_z_adc);
			printf("陀螺仪Gyro. X = %d, Y = %d, Z = %d\n", gyro_x_adc, gyro_y_adc, gyro_z_adc);
			
			// Temperature is simple so use the datasheet calculation to get deg C.
			// Note this is chip temperature.
			printf("Temp. = %f\n", (temp_adc / 340.0) + 36.53);
		}
		usleep(500000); /*500ms */
	}
	close(fd);	/* 关闭文件 */
	return NULL;
}
